<template>
  <div>
    <!-- 面包屑导航区域 -->
    <bread-crumb :breadContent="breadContent"></bread-crumb>
    <!-- 搜索与添加区域 -->
    <el-row :gutter="20">
      <el-col :span="8">
        <el-input placeholder="请输入内容"
                  v-model="queryInfo.key"
                  clearable
                  @clear="getPermissionList">
          <el-button slot="append"
                     icon="el-icon-search"
                     @click="getPermissionList"></el-button>
        </el-input>
      </el-col>
      <el-col :span="4">
        <el-button type="primary"
                   @click="addDialogVisible = true">添加权限</el-button>
      </el-col>
    </el-row>
    <br />
    <!-- 卡片视图 -->
    <el-card>
      <el-tabs v-model="activeName"
               @tab-click="handleClick">
        <el-tab-pane v-for="item in permissionType"
                     :key="item"
                     :label="item"
                     :name="item"></el-tab-pane>
      </el-tabs>

      <el-table :data="permissionList"
                border
                stripe
                :max-height="pageHeight">
        <el-table-column align="center"
                         type="index"></el-table-column>
        <el-table-column align="center"
                         label="权限名称"
                         prop="name"></el-table-column>
        <el-table-column align="center"
                         label="权限描述"
                         prop="description"></el-table-column>
        <el-table-column align="center"
                         label="权限类型"
                         prop="type"></el-table-column>
        <el-table-column align="center"
                         label="权限绑定的资源">
          <template slot-scope="scope">
            <span v-if="scope.row.resources ===null">暂未绑定资源</span>
            <!-- <span v-if="scope.row.resources.length === 1">{{scope.row.resources[0].description}}</span> -->
            <span v-else>
              {{scope.row.resources[0].description}}
              <el-tooltip class="item"
                          effect="dark"
                          content="点击查看绑定的所有资源"
                          placement="top">
                <el-popover @hide="hidePopover"
                            trigger="click"
                            placement="right"
                            width="350">
                  绑定的所有资源 <br><br>
                  <el-tag v-for="item in resourceNames"
                          :key="item"
                          style="margin-right:0.5rem;margin-bottom:0.5rem;"
                          effect="plain">
                    {{ item }}2
                  </el-tag>
                  <el-link slot="reference"
                           type="info"
                           @click="showMoreBoundResources(scope.row)">...</el-link>
                </el-popover>
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
        <el-table-column width="250px"
                         label="操作"
                         align="center">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip effect="dark"
                        content="修改权限"
                        placement="top"
                        :enterable="false">
              <el-button type="primary"
                         icon="el-icon-edit"
                         size="mini"
                         @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark"
                        content="删除权限"
                        placement="top"
                        :enterable="false">
              <el-button type="danger"
                         icon="el-icon-delete"
                         size="mini"
                         @click="removePermissionById(scope.row)"></el-button>
            </el-tooltip>
            <!-- 绑定资源按钮 -->
            <el-tooltip effect="dark"
                        content="绑定资源"
                        placement="top"
                        :enterable="false">
              <el-button type="warning"
                         icon="el-icon-circle-plus-outline"
                         size="mini"
                         @click="setResource(scope.row)"></el-button>
            </el-tooltip>
            <!-- 解绑资源按钮 -->
            <el-tooltip effect="dark"
                        content="解绑资源"
                        placement="top"
                        :enterable="false">
              <el-button type="danger"
                         icon="el-icon-remove-outline"
                         size="mini"
                         @click="unBindResource(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <pagination v-show="total>0"
                  :total="total"
                  :page.sync="queryInfo.page"
                  :limit.sync="queryInfo.size"
                  @pagination="getPermissionList" />
    </el-card>

    <!-- 添加权限的对话框 -->
    <el-dialog title="添加权限"
               :visible.sync="addDialogVisible"
               width="50%"
               @close="addDialogClosed">
      <!-- 内容主体区域 -->
      <el-form :model="addForm"
               ref="addFormRef"
               label-width="70px">
        <!-- <el-form-item label="权限名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item> -->
        <el-form-item label="权限描述"
                      prop="description">
          <el-input v-model="addForm.description"></el-input>
        </el-form-item>
        <el-form-item label="权限类型"
                      prop="type">
          <!-- <el-input v-model="addForm.type"></el-input> -->
          <el-select v-model="addForm.type"
                     clearable
                     placeholder="请选择"
                     style="width:100%"
                     @change="selectChanged">
            <el-option v-for="item in permissionType"
                       :key="item"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可绑资源"
                      prop="type">
          <el-select v-model="addForm.resourceId"
                     clearable
                     filterable
                     placeholder="请选择"
                     style="width:100%">
            <el-option v-for="item in resourceList"
                       :key="item.id"
                       :label="item.description"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="addPrivliege">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改权限的对话框 -->
    <el-dialog title="修改权限"
               :visible.sync="editDialogVisible"
               width="50%"
               @close="editDialogClosed">
      <el-form :model="editForm"
               ref="editFormRef"
               label-width="70px">
        <el-form-item label="权限名称"
                      prop="name">
          <el-input v-model="editForm.name"></el-input>
        </el-form-item>
        <el-form-item label="权限描述"
                      prop="description">
          <el-input v-model="editForm.description"></el-input>
        </el-form-item>
        <el-form-item label="权限类型"
                      prop="type">
          <!-- <el-input v-model="addForm.type"></el-input> -->
          <el-select v-model="editForm.type"
                     clearable
                     placeholder="请选择"
                     style="width:100%">
            <el-option v-for="item in permissionType"
                       :key="item"
                       :label="item"
                       :value="item">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="editPrivliege">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 绑定资源的对话框 -->
    <el-dialog title="为权限绑定资源"
               :visible.sync="permissionResourceDialogVisible"
               width="50%"
               @close="setPermissionResourceDialogClosed">
      <el-form :model="permissionInfo"
               ref="editFormRef"
               label-width="70px">
        <el-form-item label="权限名称"
                      prop="name">
          <el-input v-model="permissionInfo.name"
                    :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="权限描述"
                      prop="description">
          <el-input v-model="permissionInfo.description"
                    :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="权限类型"
                      prop="type">
          <el-input v-model="permissionInfo.type"
                    :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="绑定资源"
                      prop="type">
          <el-select v-model="resourceIds"
                     clearable
                     multiple
                     filterable
                     placeholder="请选择"
                     style="width:100%">
            <el-option v-for="item in resourceList"
                       :key="item.id"
                       :label="item.description"
                       :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer"
            class="dialog-footer">
        <el-button @click="permissionResourceDialogVisible = false">取 消</el-button>
        <el-button type="primary"
                   @click="updatePermissionResource">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
export default {
  data () {
    return {
      breadContent: ["权限管理", "权限列表"],
      // 获取权限列表的参数对象
      queryInfo: {
        key: '',
        // 当前的页数
        page: 1,
        // 当前每页显示多少条数据
        size: 10,
        type: 'menu'
      },
      total: 0,
      // 权限列表
      permissionList: [
        {
          resources: [
            {
              description: ''
            }
          ]
        }
      ],
      // 控制添加权限对话框的显示与隐藏
      addDialogVisible: false,
      // 添加权限的表单数据
      addForm: {
        // name: '',
        description: '',
        type: '',
        resourceId: ''
      },
      // 控制修改权限对话框的显示与隐藏
      editDialogVisible: false,
      // 查询到的权限信息对象
      editForm: {
        name: '',
        description: '',
        type: '',
      },
      permissionType: [],  // 权限类型
      permissionInfo: {},  // 某个权限信息
      permissionResourceDialogVisible: false,
      resourceIds: [], // 选中的资源id
      resourceList: [],  // 可绑定资源列表
      resourceNames: [],
      permissionName: '', // 要展示所有绑定资源的权限名字
      activeName: 'menu',
    }
  },
  created () {
    // 获取所有的权限
    this.getPermissionList()
    // 获取资源类型列表
    this.getResourceTypeList()
  },
  methods: {
    // 获取权限列表
    async getPermissionList () {
      const { data: res } = await this.$http.get('permission/page', { params: this.queryInfo })
      if (res.status !== 200) {
        return this.$message.error('获取权限列表失败！')
      }
      console.log(res.data.records)
      this.permissionList = res.data.records
      this.total = res.data.total
    },
    // 监听添加权限对话框的关闭事件
    addDialogClosed () {
      this.$refs.addFormRef.resetFields()
      this.resourceId = ''
    },
    // 点击按钮，添加权限
    addPrivliege () {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        // 可以发起添加权限的网络请求
        const { data: res } = await this.$http.post('permission/add', this.addForm)

        if (res.status !== 201) {
          return this.$message.error(res.message)
        }

        this.$message.success('添加权限成功！')
        // 隐藏添加权限的对话框
        this.addDialogVisible = false
        // 重新获取权限列表数据
        this.getPermissionList()
      })
    },
    // 展示编辑权限的对话框
    async showEditDialog (id) {
      console.log(id)
      const { data: res } = await this.$http.get('permission/' + id)

      if (res.status !== 200) {
        return this.$message.error(res.message)
      }

      this.editForm = res.data
      this.editDialogVisible = true
    },
    // 监听修改权限对话框的关闭事件
    editDialogClosed () {
      this.$refs.editFormRef.resetFields()
    },
    // 修改权限信息并提交
    async editPrivliege () {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return
        // 发起修改权限信息的数据请求
        const { data: res } = await this.$http.put(
          'permission/' + this.editForm.id,
          {
            name: this.editForm.name,
            description: this.editForm.description,
            type: this.editForm.type
          }
        )

        if (res.status !== 200) {
          return this.$message.error(res.message)
        }

        // 关闭对话框
        this.editDialogVisible = false
        // 刷新数据列表
        this.getPermissionList()
        // 提示修改成功
        this.$message.success('更新权限信息成功！')
      })
    },
    // 根据Id删除对应的权限信息
    removePermissionById (row) {
      this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        // 如果该权限绑定了资源，询问是否级联删除资源
        if (row.isBound) {
          this.$confirm('该权限已经绑定了资源, 确定要删除吗?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            // 选择了“确定”，级联删除资源
            console.log(row.id)
            const { data: res } = await this.$http.delete('permission/' + row.id, { params: { "cascade": true } })
            if (res.status !== 200) return this.$message.error(res.message)
            this.$message.success('删除成功！')
            this.getPermissionList()
          }).catch(() => { this.$message.info('已取消删除') })
        }
        // 没有绑定资源，普通删除
        else {
          const { data: res } = await this.$http.delete('permission/' + row.id)
          if (res.status !== 200) return this.$message.error(res.message)
          this.$message.success('删除成功！')
          this.getPermissionList()
        }
      }).catch(() => { this.$message.info('已取消删除') })
    },
    // 修改权限的有效性
    async closeAvailable (privilegeInfo) {
      const { data: res } = await this.$http.put(
        `permission/${privilegeInfo.id}/available/${privilegeInfo.available}`
      )
      if (res.status !== 200) {
        privilegeInfo.available = !privilegeInfo.available
        return this.$message.error(res.message)
      }
      this.$message.success('更新权限状态成功！')
    },
    // 展示绑定资源的对话框
    async setResource (row) {
      console.log(row)
      this.permissionInfo = row
      // 将该权限已绑定的资源id保存到resourceIds中
      this.permissionInfo.resources.forEach(item => {
        this.resourceIds.push(item.id)
      })
      // 获取该类型的资源列表
      this.getResourceList(row.type)
      // 打开绑定资源的对话框
      this.permissionResourceDialogVisible = true
    },
    // 监听绑定资源对话框的关闭事件
    setPermissionResourceDialogClosed () {
      this.permissionInfo = {}
      this.resourceIds = []
    },
    // 根据类型获取资源列表
    async getResourceList (value) {
      const { data: res } = await this.$http.get('/resource/list', { params: { type: value } })
      if (res.status !== 200) {
        return this.$message.error('获取资源列表失败！')
      }
      console.log(res.data)
      this.resourceList = res.data
    },
    // 为权限绑定资源
    async updatePermissionResource () {
      const { data: res } = await this.$http.post('permission/bind/resources',
        {
          permissionId: this.permissionInfo.id,
          resourceIds: this.resourceIds
        }
      )
      if (res.status !== 200) {
        return this.$message.error('绑定资源失败！')
      }
      this.$message.success('绑定资源成功！')
      // 隐藏绑定资源的对话框
      this.permissionResourceDialogVisible = false
      // 重新获取权限列表数据
      this.getPermissionList()
    },
    // 展示解绑资源对话框
    async unBindResource (row) {
      console.log(row)
      // 如果该权限已经绑定了资源，询问是否确定解绑资源
      if (row.isBound) {
        this.$confirm('确定要解绑该权限的资源吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          const { data: res } = await this.$http.delete(`permission/${row.id}/unbind`)
          if (res.status !== 200) {
            return this.$message.error('解绑资源失败！')
          }
          this.$message.success('解绑资源成功！')
          this.getPermissionList()
        }).catch(() => { this.$message.info('已取消解绑资源') })
      }
      // 如果该权限还未绑定资源，给出相应提示
      else {
        this.$notify({
          title: '警告',
          message: '该权限还未绑定资源,请先绑定资源！',
          type: 'warning'
        });
      }
    },

    // 获取资源类型列表
    async getResourceTypeList () {
      const { data: res } = await this.$http.get('resource/list/type')
      if (res.status !== 200) {
        return this.$message.error('获取资源列表失败！')
      }
      this.permissionType = res.data
    },

    // 添加资源对话框中select选中的事件
    async selectChanged (value) {
      console.log(value)
      this.getResourceList(value)
    },

    // 显示所有绑定的权限
    showMoreBoundResources (row) {
      console.log(row)
      row.resources.forEach(item => {
        this.resourceNames.push(item.description)
      })
    },

    // 弹出框关闭时
    hidePopover () {
      this.resourceNames = []
    },

    // 点击 tabs 标签页的事件
    async handleClick (tab, event) {
      console.log(tab, event);
      // 根据点击的tabs的name获取指定类型的资源列表
      this.queryInfo.type = tab.name
      this.getPermissionList()
    }

  }
}
</script>

<style lang="less" scoped>
</style>
